package uk.ac.cam.djjb2.mygame;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class MessageOutputStream extends DataOutputStream {
	private DataOutputStream stream;
	
	public MessageOutputStream(DataOutputStream stream) {
		super(new ByteArrayOutputStream());
		this.stream = stream;
	}
	@Override
	public void close() throws IOException {
		flush();
		ByteArrayOutputStream baos = (ByteArrayOutputStream)this.out;
		synchronized(stream) {
			stream.writeInt(this.size());
			baos.writeTo(stream);
			stream.flush();
		}
		baos.reset();
	}
}
